package com.lcf.framework.p6spy;

import cn.hutool.core.collection.CollectionUtil;
import com.p6spy.engine.logging.Category;
import jakarta.annotation.PostConstruct;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;


/**
 * 描述：p6y打印
 *
 * @author lcf
 * @since 2025/2/24 12:31
 */
@Configuration
public class P6spyLogger extends com.p6spy.engine.spy.appender.FormattedLogger {
    private final Logger log = LoggerFactory.getLogger("p6spy");

    @Value("${spring.datasource.druid.validation-query}")
    private String validationQuery;
    @Value("${org.jobrunr.database.table-prefix:jobrunr_}")
    private String tablePrefix;

    private static final List<String> SKIP = new ArrayList<>();

    @PostConstruct
    public void init() {
        SKIP.add(validationQuery);
        SKIP.add(tablePrefix);
    }

    @Override
    public void logException(Exception e) {
        this.log.info("", e);
    }

    @Override
    public void logText(String text) {
        this.log.info(text);
    }

    @Override
    public void logSQL(int connectionId, String now, long elapsed, Category category, String prepared, String sql, String url) {
        if (StringUtils.isBlank(sql) || CollectionUtil.isNotEmpty(SKIP) && SKIP.stream().anyMatch(sql::contains)) {
            return;
        }

        String msg = this.strategy.formatMessage(connectionId, now, elapsed, category.toString(), prepared, sql, url);
        if (Category.ERROR.equals(category)) {
            this.log.error(msg);
        } else if (Category.WARN.equals(category)) {
            this.log.warn(msg);
        } else if (Category.DEBUG.equals(category)) {
            this.log.debug(msg);
        } else {
            this.log.info(msg);
        }
    }

    @Override
    public boolean isCategoryEnabled(Category category) {
        if (Category.ERROR.equals(category)) {
            return this.log.isErrorEnabled();
        } else if (Category.WARN.equals(category)) {
            return this.log.isWarnEnabled();
        } else {
            return Category.DEBUG.equals(category) ? this.log.isDebugEnabled() : this.log.isInfoEnabled();
        }
    }
}
